package com.tz.service;

import com.tz.dao.AccountDao;
import com.tz.dao.AccountDaoImpl;
import com.tz.entity.Account;
import com.tz.util.MyAcUtil;
import com.tz.util.MyThreadLocal;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;

@Service
public class AccountServiceImpl implements AccountService {

	@Autowired
	private AccountDao ad;

	@Transactional
	public String transfer(int from, int to, double amount) {
		//1.检查转出账户是否存在
		Account a1=ad.get(from);
		if(a1==null){
			throw new RuntimeException("转出账号不存在");
		}
		//2.检查转入账户是否存在
		Account a2=ad.get(to);
		if(a2==null){
			throw new RuntimeException("转入账号不存在");
		}
		//3.检查转出账户余额是否充足
		if(a1.getBalance()<amount){
			throw new RuntimeException("余额不足");
		}
		//4.减操作
		a1.setBalance(a1.getBalance()-amount);

		//制造异常
		randomException();
		//5.加操作
		a2.setBalance(a2.getBalance() + amount);
		return null;
	}

	private void randomException() {
		Calendar c = Calendar.getInstance();
		int second = c.get(Calendar.SECOND);
		if(second > 30){
			throw new RuntimeException("自定义异常");
		}
	}


}
